import React, { useContext, useEffect, useState } from 'react';

const Context = React.createContext();

const ContextPage = () => {
    // 顶层状态
    const [profile, setProfile] = useState({ nickname: 'rui', age: 10 });

    useEffect(() => {
        setTimeout(() => {
            setProfile({ nickname: 'lstyr', age: 13 });
        }, 1500);
    }, []);

    return (
        <div>
            <Context.Provider value={{ profile }}>
                <Child1 />
                <Child2 />
                <Child3 />
            </Context.Provider>
            {/* <Child2 /> */}
        </div>
    );
};

class Child1 extends React.Component {
    render() {
        return (
            <Context.Consumer>
                {(ctx) => (
                    <div>
                        <h2>Child1</h2>
                        <h3>nickname: {ctx.profile.nickname}</h3>
                        <h3>age: {ctx.profile.age}</h3>
                    </div>
                )}
            </Context.Consumer>
        );
    }
}

const Child2 = () => {
    const ctx = useContext(Context);
    return (
        <div>
            <h2>Child2</h2>
            <h3>nickname: {ctx.profile.nickname}</h3>
            <h3>age: {ctx.profile.age}</h3>
        </div>
    );
};

class Child3 extends React.Component {
    static contextType = Context;
    render() {
        return (
            <div>
                <h2>Child3</h2>
                <h3>nickname: {this.context.profile.nickname}</h3>
                <h3>age: {this.context.profile.age}</h3>
            </div>
        );
    }
}

export default ContextPage;
